package com.gitee.chippyer.logger.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gitee.chippyer.logger.engine.bo.TraceEntryBO;
import com.gitee.chippyer.logger.repository.ability.mapper.TraceEntryMapper;
import com.gitee.chippyer.logger.repository.ability.po.TraceEntry;
import com.gitee.chippyer.logger.repository.converter.LogRepositoryConverter;
import com.gitee.chippyer.logger.utils.ObjectUtil;
import org.springframework.stereotype.Repository;

import java.sql.Timestamp;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Repository
class MysqlTraceStoreRepositoryImpl extends ServiceImpl<TraceEntryMapper, TraceEntry> implements TraceStoreRepository {

    @Override
    public void batchCreation(Collection<TraceEntryBO> traceEntries) {
        final List<TraceEntry> traceEntryList = traceEntries.stream()
                .map(this::toTraceEntry)
                .collect(Collectors.toList());

        super.saveBatch(traceEntryList, traceEntryList.size());
    }

    @Override
    public void creation(TraceEntryBO traceEntry) {
        super.save(this.toTraceEntry(traceEntry));
    }

    @Override
    public List<TraceEntryBO> getList(String tId) {
        if (ObjectUtil.isEmpty(tId)) {
            throw new IllegalArgumentException("[tId]不能为空");
        }

        final LambdaQueryWrapper<TraceEntry> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TraceEntry::getTId, tId);

        return super.list(wrapper).stream()
                .map(this::toTraceEntryBO)
                .collect(Collectors.toList());
    }

    @Override
    public void batchRemove(Date limitDateTime) {
        final LambdaQueryWrapper<TraceEntry> wrapper = new LambdaQueryWrapper<>();
        wrapper.le(TraceEntry::getCreateTime, limitDateTime);

        super.remove(wrapper);
    }

    private TraceEntry toTraceEntry(TraceEntryBO traceEntryBO) {
        final TraceEntry traceEntry = LogRepositoryConverter.INSTANCE.toTraceEntry(traceEntryBO);

        final Date createTime = traceEntryBO.getCreateTime();
        if (ObjectUtil.isNotEmpty(createTime)) {
            traceEntry.setCreateTime(new Timestamp(createTime.getTime()));
        }

        return traceEntry;
    }

    private TraceEntryBO toTraceEntryBO(TraceEntry traceEntry) {
        final TraceEntryBO traceEntryBO = LogRepositoryConverter.INSTANCE.toTraceEntryBO(traceEntry);

        final Timestamp createTime = traceEntry.getCreateTime();
        if (ObjectUtil.isNotEmpty(createTime)) {
            traceEntryBO.setCreateTime(new Date(createTime.getTime()));
        }

        return traceEntryBO;
    }

}
